#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<assert.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdlib.h>

#define BUFMAX 1024
#define ARGC 64
#define SEP " "
#define ENVCOUNTMAX 32
#define ENVLENMAX 64
int stlip(char* str,char* argv[])
{
  argv[0] = strtok(str,SEP);
  if(argv[0] == NULL) return -1;
  int i = 1;
  while((argv[i++] = strtok(NULL,SEP)));

  return 0;
}

void showEnv()
{
  extern char** environ;
  int i = 0;
  while(environ[i])
  {

  
  printf("%d、%s\n",i,environ[i++]);

  }
}

int main()
{
  int exit_code = 0;
  int envi = 0;
  char myenv[ENVCOUNTMAX][ENVLENMAX];
  while(1)
  {
    char* argv[ARGC] = {NULL};
    char buf[BUFMAX];
    printf("[mybash-user:李政楠]:>");
    char* s = fgets(buf,BUFMAX,stdin); 
    assert(s);
    (void)s;
    buf[strlen(buf)-1] = '\0';
    int n = stlip(buf,argv);
    if(n != 0)
    {
      continue;
    }
    if(strcmp(argv[0],"echo") == 0)
    {
      const char* env = NULL;
      if(argv[1][0] == '$')
      {
        if(argv[1][1] == '?')
        {
          printf("%d\n",exit_code);
          exit_code = 0;
          continue;
        }
      
        env = getenv(argv[1]+1);
        if(env != NULL)
        {
          printf("%s\n",env);
          exit_code = 0;
          continue;
        }
        exit_code = 1;
        continue;
      } 
    }

    if(strcmp(argv[0],"env") == 0)
    {
      showEnv();
      exit_code = 0;
      continue;
    }

    if(strcmp(argv[0],"export") == 0)
    {
      if(argv[1]== 0 || envi == ENVLENMAX)
      {
        exit_code = 1;
        fprintf(stderr,"Not found env or your envtable is already full.");
        continue;
      }
      strcpy(myenv[envi],argv[1]);
      putenv(myenv[envi++]);
     
      exit_code = 0;
      continue;
    }
    
    //加上默认颜色
    if(strcmp(argv[0],"ls") == 0)
    {
      int pos = 0;
      while(argv[pos])
      {
        pos++;
      }
      argv[pos] = (char*)"--color=auto";
    }//cd命令
    else if(strcmp(argv[0],"cd") == 0)
    {
      int n = chdir(argv[1]);
      if(n == -1)
      {
       fprintf(stderr,"not found director\n"); 
      }
      continue;
    }
    pid_t pid = fork();
    int status;
    if(pid == 0)
    {
      execvp(argv[0],argv);
      exit(1);
    }

    int ref =  waitpid(pid,&status,0);
    if(ref > 0)
    {
      exit_code = WEXITSTATUS(status);
    }
  }

  




  return 0;
}
